<template>
    <div class="interact-wrapper container-channel" ref="interactWrapper">
        <mescroll-vue 
            ref="mescroll" 
            :up="mescrollUp" 
            :down="mescrollDown"
            @init="mescrollInit"
        >
            <CountDown 
                :dateTime="dateTime" 
                :timeStamp="timeStamp"
                v-if="live && live.live_status === 1"
            ></CountDown>
            <!-- /倒计时 -->
            <!-- <div class="concern text-center">
                <p>本直播是由微光Live创建</p>
                <img :src="codeUrl" alt="">
                <p>手机端请长按二维码，关注公众号</p>
            </div> -->
            <!-- /concern -->
            <!-- <div class="tip-empty text-center" v-if="commentsNone"><p>没有更多评论</p></div>
            <div class="tip-empty text-center" style="margin: 10px 0;" v-if="showChatLists.length && newestComentsNone"><p>没有最新评论</p></div> -->
            <ul class="chat-lists"
                v-if="showChatLists.length"  
            >
                <li class="chat-lists-item"
                v-for="(item, index) in showChatLists"
                :key="index"
                >
                    <template  v-if="item.type == 1">
                        <div class="media media-chat">
                            <div class="media-object"><img :src="item.avatar" alt="" class="media-object-avtar" :style="{'background': 'url('+avatarUrl+') no-repeat center center'}"></div>
                            <div class="media-body">
                            <div class="media-head">
                                <h4 class="media-head-title">{{item.nickname}}</h4>
                            </div>
                            <div class="media-body">
                                <div class="media-chat-word media-body-content">
                                <i class="arrow"></i>
                                    <!-- <p class="media-chat-text media-chat-content">{{item.content || ''}}！</p> -->
                                    <ChatFaceItem :contentStr="item.content"></ChatFaceItem>
                                </div>
                            </div>
                            </div>
                        </div> 
                    </template>
                    <template v-else-if="item.type == 2">
                        <div class="media media-chat">
                            <div class="media-object"><img :src="item.avatar" alt="" class="media-object-avtar"></div>
                            <div class="media-body">
                            <div class="media-head">
                                <h4 class="media-head-title">{{item.nickname}}</h4>
                            </div>
                            <div class="media-body">
                                <div class="media-chat-picture media-body-content">
                                <i class="arrow"></i>
                                <div class="media-chat-img media-chat-content"><img :src="pictureUrl"></div>
                                </div>
                            </div>
                            </div>
                        </div>
                    </template>
                    <template v-else-if="item.type == 3">
                        <div class="media media-chat">
                            <div class="media-object"><img :src="item.avatar" alt="" class="media-object-avtar"></div>
                            <div class="media-body">
                            <div class="media-head">
                                <h4 class="media-head-title">{{item.nickname}}</h4>
                            </div>
                            <div class="media-body">
                                <div class="media-chat-packet media-body-content">
                                <i class="arrow"></i>
                                <div class="media-chat-content">
                                    <div class="media-chat-main clearfix">
                                        <div class="media-object pull-left"><img :src="hongbaoUrl" alt=""></div>
                                        <div class="media-title">恭喜发财，大吉大利</div>
                                        <p class="media-status">红包已领完</p>
                                    </div>
                                    <div class="media-chat-describe">普通红包</div>
                                </div>
                                </div>
                            </div>
                            </div>
                        </div>
                    </template>
                    <!-- <div class="media media-chat">
                        <div class="media-object"><img :src="item.avatar" alt="" class="media-object-avtar"></div>
                        <div class="media-body">
                        <div class="media-head">
                            <h4 class="media-head-title">test</h4>
                        </div>
                        <div class="media-body">
                            <div class="media-chat-word media-body-content">
                            <i class="arrow"></i>
                            <ChatFaceItem :contentStr="item.content"></ChatFaceItem>
                            
                            </div>
                        </div>
                        </div>
                    </div> -->
                </li>

            </ul>
            <div class="tip-empty text-center" v-else style="margin: 40px 0;"><p>还没有评论</p></div>

            <!-- <template>
                <p class="text-center color-gray" style="font-size: 12px; line-height: 2;">22:32</p>
                <div class="red-receive-list text-center">
                    <p><router-link to="/redDetail"><img :src="hongbaoUrl" class="red-receive-img">航飞分鸟领取了你的红包</router-link></p>
                </div>
                <div class="red-receive-list text-center">
                    <p><router-link to="/redDetail"><img :src="hongbaoUrl" class="red-receive-img">万博考研教育领取了你的红包</router-link></p>
                </div>
            </template> -->
            
                <!-- <RedPacket :src="avatarUrl"></RedPacket> -->
            
        </mescroll-vue>


        <div class="option-bar text-center">
            <router-link to="/invitation" type="button" class="lm-button button-invitation">邀</router-link>
            <button type="button" class="lm-button button-given" @click.stop="showGratuity = true">赏</button>
            <button type="button" class="lm-button button-praise relative">
                <i class="icon icon-praise"></i>
                <span class="bubble-origin" ref="bubbleOrigin">
                <!-- <i class="van-icon van-icon-like"
                    v-for="(item, index) in bubbleLists"
                    :key="index"
                    :style="{'top': item.top+'px', 'left': item.left+'px', 'color': item.color, 'opacity': item.opacity}"
                ></i> -->
                </span>
            </button>
            <span class="counts">{{live.likes || 0}}</span>
        </div>
        <!-- /option-bar -->

        <div class="option-groups-panel" v-if="componentName == 'chat'">
            <div class="input-bar">
                <span class="icon-box" @click="toggleFaceDisplay"><i class="icon icon-expression"></i></span>
                <div class="input-box">
                <!-- <pre
                    contenteditable="true"
                    v-html="inputContent"
                    @keyup.enter="submitContent"
                    @input="changeInputContent"
                    style="-webkit-user-select: auto"
                    ref="divInput"
                ></pre> -->
                <input type="text" placeholder="来说点什么吧" class="input-text pull-left"
                    v-model="inputContent"
                    @keyup.enter="submitContent"
                    ref="textInput"
                />
                </div>

                <span class="icon-box icon-gift-box" @click="isShowGiftPanel = true"><em class="icon-gift"></em></span>
                <span class="icon-box" @click.stop="toggleToolpanel"><i class="icon icon-add-circle"></i></span>
                <span class="button-send"
                    v-show="showSendButton"
                    @click.stop="sendContent"
                >发送</span>
            </div>

            <QQfaceItem
                @insert-face="insertFace"
                @delete-input-content="deleteContent"
                :isShow="inputPanel == 'face'"
            ></QQfaceItem>
            <!-- /QQfaceItem -->

            <ToolPanel
                :isShow="inputPanel == 'tool'"
                @sign-action="signAction"
            ></ToolPanel>

        </div>
        <!-- /option-groups-panel工具栏集合 -->
        
        <van-popup 
            v-model="showGratuity"
            get-container="#app"
            class="popup-gratuity"
        >
            <Gratuity
                @close-gratuity-dialog="showGratuity = false"
                @show-other-money="showOtherMoney = true"
            ></Gratuity>
        </van-popup>

        <!-- 打赏 -->
        <van-popup 
            v-model="showOtherMoney"
            overlay="false"
            class="popup-other-money"
            get-container="#app" 
        >
            <OtherAmounts
                @hide-other-money="showOtherMoney = false"
                @set-other-money="setOtherMoney"
            ></OtherAmounts>
        </van-popup>

        <van-popup 
            class="popup-gift"
            v-model="isShowGiftPanel"
            position="bottom"
        >
            <GiftPanel 
                @give-gifts="giveGifts"
                :giftLists="giftLists"
            ></GiftPanel>
        </van-popup>
        <!-- /展示礼物面板 -->

    </div>
</template>

<script>
import faceMaps from '@/modal/face.json';
import CountDown from '@/views/Channel/CountDown';
import ToolPanel from '@/components/Live/ToolPanel';
import OtherAmounts from '@/views/RedPacket/Other';
import Gratuity from '@/views/RedPacket/Gratuity';
import GiftPanel from '../GiftPanel';
import QQfaceItem from '@/components/QQface';
import ChatFaceItem from '@/components/Live/ChatFaceItem';

import store from '@/store/index';
import strophe from 'strophe.js';
import WebIM from 'easemob-websdk';
import { clearTimeout, setTimeout } from 'timers';
import MescrollVue from 'mescroll.js/mescroll.vue'
import { mapState } from 'vuex';
import {getGiftLists, addComment, getCommentlist} from '@/api';

export default {
    components: {
        CountDown,
        ToolPanel,
        OtherAmounts,
        Gratuity,
        GiftPanel,
        QQfaceItem,
        ChatFaceItem,
        MescrollVue
    },
    props: {
        live: { type: Object, default: {}},
        //commentsArray: { type: Array, default: []},
        timeStamp: { type: Number },
        dateTime: { type: String },
        componentName: { type: String }
    },
    //props:['live', 'commentsArray', 'timeStamp', 'dateTime'],
    data() {
        return {
            timeStamp2: new Date('2019-09-16 18:30').getTime(),
            active: 0,
            isRising: false,
            riseBubbleTimer: null,
            heartCounts: 10,
            bubbleLists: [],  // 心形气泡数量
            codeUrl: require('@/assets/img/2vcode.png'),
            pictureUrl: require('@/assets/img/chat_picture.png'),
            avatarUrl: require('@/assets/img/avtar_list.png'),
            hongbaoUrl: require('@/assets/img/hongbao.png'),
            showSendButton: false,
            showOtherMoney: false,
            // 是否显示赏-红包弹窗
            showGratuity: false,
            inputPanel: '',
            chatLists: [],
            commentsArray: [],
            inputContent: '',
            sqlContent: '',
            isShowGiftPanel: false,
            imconn: {},   //im 连接对象
            giftLists: [],

            newestComentsNone: false,
            commentsNone: false, // 是否有历史数据
            // 滚动条
            mescroll: null,
            mescrollDown: {
                auto: false,
                callback: this.downCallback
            },
            mescrollUp: {
                auto: false,
                isBounce: true,
                callback: this.upCallback,
                offset: 300,
                onScroll: this.onContentSlideScroll,
                noMoreSize: 3
            },
            interactMaps: {}
        };
    },
    created(){
        this.getCommentlist(1, (result)=>{
            this.commentsArray = result.data.map((item)=>{
                item['content'] = item.content.content;
                item['type'] = item.content_type || 1;
                return item;
            });
        });
        // getCommentlist({page: 1}).then((response)=>{
        //     console.log(response)
        //     let result = response.data;
        //     this.interactMaps = result;
        //     this.commentsArray = result.data.map((item)=>{
        //         item['content'] = item.content.content;
        //         item['type'] = item.content_type || 1;
        //         return item;
        //     });
        // });
    },
    computed: {
        ...mapState({
           userInfo: state => state.userinfo 
        }),
        showChatLists(){
            return [...this.commentsArray, ...this.chatLists]
        }
    },
    methods: {
        qipao(){
            let _this = this;
            var BubbleHearts = (this, function() {
                "use strict";

                function t(t, n, r) {
                    var i = e.uniformDiscrete(89, 91) / 100,
                        o = 1 - i,
                        u = (e.uniformDiscrete(45, 60) + e.uniformDiscrete(45, 60)) / 100,
                        a = function(t) {
                            return t > i ? Math.max(((1 - t) / o).toFixed(2), .1) * u : u
                        },
                        c = e.uniformDiscrete(-30, 30),
                        f = function(t) {
                            return c
                        },
                        h = 10,
                        s = n.width / 2 + e.uniformDiscrete(-h, h),
                        d = (n.width - Math.sqrt(Math.pow(t.width, 2) + Math.pow(t.height, 2))) / 2 - h,
                        l = e.uniformDiscrete(.8 * d, d) * (e.uniformDiscrete(0, 1) ? 1 : -1),
                        m = e.uniformDiscrete(250, 400),
                        w = function(t) {
                            return t > i ? s : s + l * Math.sin(m * (i - t) * Math.PI / 180)
                        },
                        v = function(e) {
                            return t.height / 2 + (n.height - t.height / 2) * e
                        },
                        p = e.uniformDiscrete(14, 18) / 100,
                        g = function(t) {
                            return t > p ? 1 : 1 - ((p - t) / p).toFixed(2)
                        };

                    //console.log('m----:',m)

                        //r.translate(o, u), r.scale(n, n), r.rotate(i * Math.PI / 180), r.globalAlpha = g(e), r.drawImage(t, -t.width / 2, -t.height / 2, t.width, t.height), r.restore()
                    return function(e) {
                        if(!(e >= 0)) return !0;
                        r.save();
                        var n = a(e),
                            i = f(e),
                            o = w(e),
                            u = v(e);
                           // console.log(o, u)
                        r.translate(o, u), r.scale(n, n), r.rotate(i * Math.PI / 180), r.globalAlpha = g(e), r.drawImage(t, -t.width / 2, -t.height / 2, 30, 30), r.restore()
                    }
                }
                var e = function(t) {
                        var e = t,
                            n = Math.floor,
                            r = Math.random;
                        return t.uniform = function(t, e) {
                            return t + (e - t) * r()
                        }, t.uniformDiscrete = function(t, r) {
                            return t + n((r - t + 1) * e.uniform(0, 1))
                        }, t
                    }({}),
                    n = function(t, e) {
                        if(!(t instanceof e)) throw new TypeError("Cannot call a class as a function")
                    },
                    r = function() {
                        function t(t, e) {
                            for(var n = 0; n < e.length; n++) {
                                var r = e[n];
                                r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(t, r.key, r)
                            }
                        }
                        return function(e, n, r) {
                            return n && t(e.prototype, n), r && t(e, r), e
                        }
                    }(),
                    i = window.requestAnimationFrame || window.webkitRequestAnimationFrame || function(t) {
                        return setTimeout(t, 16)
                    },
                    o = function() {
                        function o() {
                            n(this, o);
                            var t = this.canvas = document.createElement("canvas"),
                                e = this.context = t.getContext("2d"),
                                r = this._children = [],
                                u = function n() {
                                    i(n), e.clearRect(0, 0, t.width, t.height);
                                   // console.log(22)

                                    for(var o = 0, u = r.length; o < u;) {
                                        var a = r[o];
                                        a.render.call(null, (a.timestamp + a.duration - new Date) / a.duration) ? (r.splice(o, 1), u--) : o++
                                    }
                                };

                            i(u)
                        }
                        return r(o, [{
                            key: "bubble",
                            value: function(n) {
                                //console.log('~~~~~~~~~~~~~~~~')
                                var r = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : e.uniformDiscrete(2400, 3600),
                                    i = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : t(n, this.canvas, this.context);
                                
                                return this._children.push({
                                    render: i,
                                    duration: r,
                                    timestamp: +new Date
                                }), this
                            }
                        }]), o
                    }();
                return o
            })();

            
            // 图片地址在此处更换  可换成你的图片
            var assets = [
                require('../img/1.png'),
                require('../img/2.png'),
                require('../img/3.png'),
                require('../img/4.png'),
                require('../img/5.png'),
                require('../img/6.png'),
                require('../img/7.png')
            ];
            assets.forEach(function(src, index) {
                assets[index] = new Promise(function(resolve) {
                    var img = new Image;
                    img.onload = resolve.bind(null, img);
                    img.src = src;
                });
            });

            Promise.all(assets).then(function(images) {

                var random = {
                    uniform: function(min, max) {
                        return min + (max - min) * Math.random();
                    },
                    uniformDiscrete: function(i, j) {
                        return i + Math.floor((j - i + 1) * random.uniform(0, 1));
                    },
                };

                var stage = new BubbleHearts();
                var canvas = stage.canvas;
                canvas.width = 90;
                canvas.height = 300;
                canvas.style['width'] = '90px';
                canvas.style['height'] = '320px';
                canvas.style['position'] = 'absolute';
                canvas.style['bottom'] = 0;
                canvas.style['right'] = 0; //'54px';

               // _this.$refs.interactWrapper.appendChild(canvas);
               _this.$refs.bubbleOrigin.appendChild(canvas);
               
                //journal-reward 为赏桃的按钮 
                document.querySelector('.button-praise').addEventListener('click', function() {
                    //随机飘动
                    stage.bubble(images[random.uniformDiscrete(0, images.length - 1)]);
                }, false);

            });
        },
        toggleToolpanel(){
            this.inputPanel = (this.inputPanel == 'tool') ? '' : 'tool';
        },
        onContentSlideScroll(scroll, offsetY){

        },
        getCommentlist(page, successCallback){
            if(this.commentsNone) return;
            getCommentlist({page: page}).then((response)=>{
                let result = response.data;
                this.interactMaps = result;

                this.commentsNone = result.current_page === result.last_page;
                this.mescroll.endSuccess(true)
                typeof successCallback === 'function' && successCallback(result)
            });
        },
        mescrollInit (mescroll) {
            this.mescroll = mescroll;  // 如果this.mescroll对象没有使用到,则mescrollInit可以不用配置
        },
        upCallback(){
            console.log('abc~~~~~~~')
            // console.log(this.commentsNone)
            // if(this.commentsNone) return;
            // console.log(++this.interactMaps.current_page)
            // this.getCommentlist(++this.interactMaps.current_page,(result)=>{
            //     this.mescroll.endSuccess(true);
            //     let commentsArray = result.data.map((item)=>{
            //         item['content'] = item.content.content;
            //         item['type'] = item.content_type || 1;
            //         return item;
            //     });
            //     this.commentsArray.concat(commentsArray);
            // });
        },
        downCallback(){
            if(this.commentsNone) this.mescroll.endSuccess();
            this.getCommentlist(this.interactMaps.current_page+1,(result)=>{
                
                let commentsArray = result.data.map((item)=>{
                    item['content'] = item.content.content;
                    item['type'] = item.content_type || 1;
                    return item;
                });

                this.commentsArray = [...commentsArray, ...this.commentsArray];
                //this.commentsArray.concat(commentsArray);
                this.$nextTick(()=>{
                    this.mescroll.endSuccess(true);
                });
            });
        },
        changeOffset(){
            let risingBubbles = this.bubbleLists.filter((item)=>{
                return item.top > -300 && item.opacity > 0;
            //return item.opacity > 0;
            });

            if(risingBubbles.length){
            console.log(risingBubbles)
                this.isRising = true;
                this.riseBubbleTimer = setTimeout(()=>{
                    this.bubbleLists = this.bubbleLists.map((item)=>{
                        //item.opacity -= 0.1;
                        //item.top -= 5;
                        //item.left = Math.floor(Math.random() * (30 + 10)) - 10;
                        return item;
                    });
                    this.changeOffset();
                }, 100);
            }else{

                clearTimeout(this.riseBubbleTimer);
                this.riseBubbleTimer = null;
                this.isRising = false;
            }
        },
        riseBubble(){
            let colors = ['#cea835', '#ce8119', '#bf1d1a', '#c55784', '#ca378f', '#c02158', '#80ad4e', '#529154', '#32af98', '#1d4890', '#544098', '#3ba8f2'];
            // 往气泡数组里面添加内容
            let key = Math.floor(Math.random() * 12 + 1);
            let item = {
                color: colors[key],
                opacity: 1,
                left: Math.floor(Math.random() * (20 + 10)) - 20,
                top: Math.floor(Math.random() * (-10+40)) - 40,
            }

            setTimeout(()=>{
                this.bubbleLists.push(item);
            }, 30)
            
            if(!this.isRising) this.changeOffset();
        },
        toggleFaceDisplay(){
            this.inputPanel = this.inputPanel == 'face' ? '' : 'face';
        },
        sendContent(){
            this.inputPanel = '';
            this.submitContent();
        },
        submitContent(){
            var that = this;
            let formatedStr = this.inputContent.replace(/<\/?.+?>/g, function(match, index, orginString){
                var indexStr = match.replace(/<i data-index=\"(.*?)\"([^\[]*)/gm,'[$1.gif]');
                return indexStr.replace('</i>', '');
            });

            let content = {
                type: '1',
                nickname: this.userInfo.nickname,
                avatar: this.userInfo.avatar,
                content: formatedStr
            };
            console.log('内容：@@@', content)

            //this.chatLists = [...this.chatLists, ...[content]];

            // 添加评论入库
            addComment({
                live_id: this.live.id,
                content_type: 1, //聊天类型1. 普通文本，2.图片，3.送礼物 4.打赏，5.群红包
                is_reply: 0,
                to_id: '',
                to_user_id: '',
                content: {content: formatedStr}
            }).then((response)=>{
                if(response.code === 0){
                    this.chatLists = [...this.chatLists, ...[content]];
                }
                //console.log(response)
            }).catch((err)=>{
                console.log(err)
                this.chatLists = [...this.chatLists, ...[content]];
            });

            //聊天室文本消息
            var id = this.imconn.getUniqueId();
            var msg = new WebIM.message('txt', id);
            var option = {
                msg: formatedStr,          // 消息内容
                to: '93487298052097',               // 接收消息对象(聊天室id)
                roomType: true,                  // 群聊类型，true时为聊天室，false时为群组
                ext: content,                         // 扩展消息
                success: function (resp) {
                    console.log('提交内容', resp)
                    //this.sqlContent = this.toHTML(this.inputContent)
                    that.chatLists.push({content: formatedStr});
                    that.inputContent = '';
                    that.$refs.inputText.blur();
                },                               // 对成功的相关定义，sdk会将消息id登记到日志进行备份处理
                fail: function (resp,res,fff) {

                }                                // 对失败的相关定义，sdk会将消息id登记到日志进行备份处理
            };
            msg.set(option);
            msg.setGroup('groupchat');
            console.log(msg.body)
            this.imconn.send(msg.body);
            this.inputContent = '';
        },
        giveGifts(params){
            console.log(params)
            this.isShowGiftPanel = false;
        },
        setOtherMoney(money){
            console.log('其他金额',money);
            this.showOtherMoney = false;
            this.showGratuity = false;
        },
        signAction(){ this.$toast("您已签到！"); },
        insertFace(faceInfo){
            let name = Object.values(faceMaps).find((item)=>{ return item.index == faceInfo.gifIndex})['text'];
            let girUrl = require(`@/assets/gif/${faceInfo.gifIndex}.gif`);
            let gifString = `<img src="${girUrl}" class="img-gif" />`;
            //this.inputContent = this.$refs.divInput.innerHTML + `${gifString}`;
            //this.inputContent = this.$refs.divInput.innerHTML + name; //`${faceInfo.htmlString}`(直接插入图片);
            this.inputContent += name;
            //this.keepLastIndex(this.$refs.divInput);
            this.$refs.textInput.focus();
        },
        changeInputContent(){
            let inputContentDOM = this.$refs.divInput;
            this.inputContent = inputContentDOM.innerHTML;
            this.keepLastIndex(inputContentDOM);
        },
        keepLastIndex(obj) {
            setTimeout(()=>{
                if (window.getSelection) { //ie11 10 9 ff safari
                    obj.focus(); //解决ff不获取焦点无法定位问题
                    var range = window.getSelection(); //创建range
                    range.selectAllChildren(obj); //range 选择obj下所有子内容
                    range.collapseToEnd(); //光标移至最后
                } else if (document.selection) { //ie10 9 8 7 6 5
                    var range = document.selection.createRange(); //创建选择对象
                    //var range = document.body.createTextRange();
                    range.moveToElementText(obj); //range定位到obj
                    range.collapse(false); //光标移至最后
                    range.select();
                }
            }, 5)
        },
        deleteContent(){
            this.inputContent = this.inputContent.slice(0, -1);
            //this.inputContent = this.$refs.divInput.innerHTML.slice(0, -1);
            // setTimeout(()=>{
            //     this.keepLastIndex(this.$refs.divInput);
            //     //改变scrollTop的位置
            // },5);
            setTimeout(()=>{
                this.$refs.textInput.focus();
            }, 50);
        },
        formatedMessage(data){
            
        },
        //初始化IM
        initIM(){
            var that = this;
            var uname = 'lirui8';//注册用户名
            var upwd = '123456';//注册密码
            WebIM.config = {
                xmppURL: (window.location.protocol === "https:" ? "https:" : "http:") + "//im-api-v2.easemob.com/ws",
                apiURL: (window.location.protocol === "https:" ? "https:" : "http:") + "//a1.easemob.com",
                appkey: "1111190810090316#ceshiweiguang",
                Host: "easemob.com",
                https: true,
                isHttpDNS: false,
                isMultiLoginSessions: true,
                isWindowSDK: false,
                isSandBox: false,
                isDebug: true,
                isStropheLog: false,
                autoReconnectNumMax: 5,
                autoReconnectInterval: 2,
                isWebRTC: window.RTCPeerConnection && /^https\:$/.test(window.location.protocol),
                i18n: "cn",
                isAutoLogin: true,
                p2pMessageCacheSize: 500,
                delivery: true,
                groupMessageCacheSize: 200,
                loglevel: "ERROR",
                enableLocalStorage: true
            }

            //创建连接
            this.imconn = WebIM.conn = new WebIM.connection({
                appKey: WebIM.config.appkey,
                isHttpDNS: WebIM.config.isHttpDNS,
                isMultiLoginSessions: WebIM.config.isMultiLoginSessions,
                host: WebIM.config.Host,
                https: WebIM.config.https,
                url: WebIM.config.xmppURL,
                apiUrl: WebIM.config.apiURL,
                isAutoLogin: false,
                heartBeatWait: WebIM.config.heartBeatWait,
                autoReconnectNumMax: WebIM.config.autoReconnectNumMax,
                autoReconnectInterval: WebIM.config.autoReconnectInterval,
                isStropheLog: WebIM.config.isStropheLog,
                delivery: WebIM.config.delivery
            })
            //事件监听
            this.imconn.listen({
                onOpened: function (message) {          //连接成功回调
                    var myDate = new Date().toLocaleString();
                    console.log("%c [opened] 连接已成功建立", "color: green");
                    console.log(myDate);
                    // rek();
                    // alert(myDate + "登陆成功")
                },
                onClosed: function (message) {
                    console.log("onclose:" + message);
                },         //连接关闭回调
                onTextMessage: function (message) {

                    that.chatLists = [...that.chatLists, ...[message.ext]]
                    console.log('onTextMessage:', message)
                    //接受文本消息
                    // that.chatLists.push({content: message.data});
                    // console.log('onTextMessage: ', message);
                    // if (message.ext.conferenceId != undefined) {
                    //     var truthBeTold = window.confirm((message.from + "邀请您加入会议"));
                    //     if (truthBeTold) {
                    //         emedia.mgr.joinConference(message.ext.conferenceId, message.ext.password, "进入会议").then(function () {
                    //             console.log("********加入会议成功*******")
                    //         }).catch(function (error) {
                    //             console.log("加入会议失败")
                    //         })
                    //     }
                    // }
                },    //收到文本消息
                onEmojiMessage: function (message) {
                    console.log('onEmojiMessage: ', message);
                },   //收到表情消息
                onPictureMessage: function (message) {
                    console.log('onPicMessage: ', message);
                }, //收到图片消息
                onCmdMessage: function (message) {
                    console.log('onCmdMessage: ', message);
                },     //收到命令消息
                onAudioMessage: function (message) {
                    console.log('onAudioMessage: ', message);
                },   //收到音频消息
                onLocationMessage: function (message) {
                    console.log('onLocMessage: ', message);
                },//收到位置消息
                onFileMessage: function (message) {
                    console.log('onFileMessage: ', message);
                },    //收到文件消息
                recallMessage: function (message) {
                    console.log('recallMessage', message);
                }, //消息撤回
                onVideoMessage: function (message) {
                    console.log('onVideoMessage: ', message);
                    var node = document.getElementById('getVideo');
                    var option = {
                        url: message.url,
                        headers: {
                            'Accept': 'audio/mp4'
                        },
                        onFileDownloadComplete: function (response) {
                            var objectURL = WebIM.utils.parseDownloadResponse.call(this.imconn, response);
                            node.src = objectURL;
                        },
                        onFileDownloadError: function () {
                            console.log('File down load error.')
                        }
                    };
                    WebIM.utils.download.call(this.imconn, option);
                },   //收到视频消息
                onPresence: function (message) {
                    var myDate = new Date().toLocaleString();
                    console.log('onPresence: ', myDate + JSON.stringify(message));
                    switch (message.type) {
                        case 'subscribe': // 对方请求添加好友
                            var truthBeTold = window.confirm((message.from + "申请添加您为好友:"));
                            if (truthBeTold) {
                                // 同意对方添加好友
                                this.imconn.subscribed({
                                    to: message.from,
                                    message: "[resp:true]"
                                });
                                console.log("同意添加好友");
                            } else {
                                // 拒绝对方添加好友
                                this.imconn.unsubscribed({
                                    to: message.from,
                                    message: "rejectAddFriend" // 拒绝添加好友回复信息
                                });
                                console.log("拒绝添加好友");
                            }
                            break;
                        case 'subscribed': // 对方同意添加好友，已方同意添加好友
                            break;
                        case 'unsubscribe': // 对方删除好友
                            break;
                        case 'unsubscribed': // 被拒绝添加好友，或被对方删除好友成功
                            break;
                        case 'memberJoinPublicGroupSuccess': // 成功加入聊天室
                            console.log('join chat room success' + myDate);
                            console.log(new Date().toLocaleString());
                            break;
                        case 'joinChatRoomFaild': // 加入聊天室失败
                            console.log('join chat room faild');
                            break;
                        case 'joinPublicGroupSuccess': // 意义待查
                            console.log('join public group success', message.from);
                            break;
                        case 'createGroupACK':
                            this.imconn.createGroupAsync({
                                from: message.from,
                                success: function (option) {
                                    console.log('Create Group Succeed');
                                }
                            });
                            break;
                    }
                },       //处理“广播”或“发布-订阅”消息，如联系人订阅请求、处理群组、聊天室被踢解散等消息
                onRoster: function (message) {
                    console.log("onRoster", message);
                },         //处理好友申请
                onInviteMessage: function (message) {
                    console.log('Invite');
                },  //处理群组邀请
                //本机网络连接成功
                onOnline: function () {
                    console.log("onOnline");
                },   
                //本机网络掉线               
                onOffline: function () {
                    console.log('offline');
                },                 
                onError: function (message) {
                    console.log('onError: ', message);

                },          //失败回调
                onBlacklistUpdate: function (list) {       //黑名单变动
                    // 查询黑名单，将好友拉黑，将好友从黑名单移除都会回调这个函数，list则是黑名单现有的所有好友信息
                    console.log(list);
                },
                onReceivedMessage: function (message) {
                    var bodyId = message.id;         // 需要发送已读回执的消息id
                    var msgId = message.mid;         // 需要发送已读回执的消息id
                    var msg = new WebIM.message('read', msgId);
                    msg.set({
                        id: bodyId
                        ,to: message.from
                    });
                    that.imconn.send(msg.body);
                    console.log('onReceivedMessage: ', message);
                },    //收到消息送达服务器回执
                onDeliveredMessage: function (message) {
                    console.log('onDeliveredMessage：', message);
                },   //收到消息送达客户端回执
                onReadMessage: function (message) {
                    console.log('onReadMessage: ', message);
                },        //收到消息已读回执
                onCreateGroup: function (message) {
                    console.log('onCreateGroup: ', message);
                },        //创建群组成功回执（需调用createGroupNew）
                onMutedMessage: function (message) {
                    console.log('onMutedMessage: ', message);
                }         //如果用户在A群组被禁言，在A群发消息会走这个回调并且消息不会传递给群其它成员
            });

            //注册
            var option = {
                username: uname,
                password: upwd,
                appKey: WebIM.config.appkey,
                success: function () {
                    console.log('注册成功');
                },
                error: function (res) {
                    console.log('注册失败' , res);
                },
                apiUrl: WebIM.config.apiURL
            };
            this.imconn.signup(option);

            //登录
            var options = {
                apiUrl: WebIM.config.apiURL,
                user: uname,
                pwd: upwd,
                appKey: WebIM.config.appkey
            };
            this.imconn.open(options);

            //加入聊天室
            setTimeout(function () {
                that.imconn.joinChatRoom({
                    roomId: '93487298052097',// 聊天室id
                    success: function () {
                        console.log(new Date().toLocaleString());
                    },
                    fail: function(res){
                        console.log(123123124124);
                        console.log(res);
                    }
                });
            },2000);

            // 关闭连接
            // this.imconn.close();

        },
    },
    mounted() {
        this.qipao()
        this.initIM();

        getGiftLists(this.live.id).then((response)=>{
            if(response.code === 0){
                this.giftLists = response.data;
            }
            console.log(response)
        });
        
        document.body.addEventListener('focusout', () => { //软键盘关闭事件
            let scrollTop = document.scrollTop;
            window.scrollTo(0,0);
        })
    },
    watch:{
        // 监控输入内容,如果长度>0则显示发送按钮
        inputContent(){
            this.showSendButton = this.inputContent.length > 0;
        }
    } 
};
</script>
<style lang="scss" scoped>
@import '@/assets/config.scss';

.interact-wrapper {
    height: 100%;
    padding-bottom: 104px;
    position: relative;
    overflow: hidden;

    .container-inner{
        height: 100%;
        position: relative;
    }
}
.concern {
    p { font-size: 24px; line-height: 2.5; color: #666; }
    img { width: 250px; height: 250px; vertical-align: middle; }
}


.popup-gratuity, .popup-other-money {
    width: 100%;
    height: 100%;
    background: none;
}

.chat-lists {
  padding: 40px 35px;
  .chat-lists-item{
    margin-bottom: 20px;
    &:last-child{margin-bottom: 0;}
  }
}

.media-chat {
  display: flex;
  .media-object {
    width: 80px;
    height: 80px;
    margin-right: 20px;
  }

  .media-object-avtar {
    display: block;
    width: 100%;
    height: 100%;
    border-radius: 100%;
  }
  .media-head {
    margin-bottom: 15px;
  }
  .media-head-title {
    font-size: 28px;
    line-height: 36px;
  }

  .media-body-content {
    padding: 6px;
    background-color: $color-white;
    border-radius: 8px;
    position: relative;
    .arrow {
      position: absolute;
      border-width: 24px 0 0 30px;
      border-style: solid;
      border-color: #fff transparent transparent transparent;
      left: -24px;
      top: 24px;
      transform: rotate(20deg);
    }
  }

  .media-chat-word {
    max-width: 480px;;
    padding: 10px 16px;
  }
  .media-chat-text {
    font-size: 28px;
    color: #333;
  }

  .media-chat-content {
    background-color: $color-white;
    position: relative;
    z-index: 5;;
  }
  .media-chat-picture {
    width: 320px;
  }
  .media-chat-img { height: 174px;}
}


.media-chat-packet{
  max-width: 434px;
  padding: 0 !important;
  color: #fff;
  font-size: 24px;

  .media-chat-main {
    padding: 22px 26px;
    background: #f7ba69;
  }

  .arrow {
    width: 18px;
    height: 18px;
    border: 0 none !important;
    left: -5px !important;
    background-color: #f7ba69;
    transform: rotate(45deg) !important;

  }
  .media-object {
    width: 60px;
    height: 76px;
    margin-right: 24px;
    overflow: hidden;
  }
  .media-chat-content {
    border-radius: 8px;
    overflow: hidden;
  }
  .media-title {
    font-size: 30px;
    font-weight: bold;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .media-status {
    font-size: 24px;
  }
  .media-chat-describe {
    height: 38px;
    padding-left: 28px;
    font-size: 24px;
    line-height: 38px;
    color: #999;
    background-color: #fff;
  }
}


.red-receive-list {
  margin-bottom: 40px;;
  font-size: 24px;
  color: #999;
  line-height: 40px;
  a { color: #999; }
}

.red-receive-img {
  width: 28px;
  height: 40px;
  margin-right:12px;
  vertical-align: middle;
}



.option-bar {
  $size: 80px;
  position: absolute;
  right: 35px;
  bottom: 130px;
  width: $size;
  font-size: 0;
  .lm-button {
    display: inline-block;
    width: $size;
    height: $size;
    margin-bottom: 20px;
    font-size: 30px;
    color: $color-white;
    line-height: $size;
    text-align: center;
    border-radius: 100%;
    position: relative;
    &:last-child{ margin-bottom: 10px; }
    

    &.button-invitation { background-color: $blue; }
    &.button-given { background-color: #fcba2e; }
    &.button-praise { background-color: #fc2876; font-size: 48px;}

    .bubble-origin {
      width: 84px;
      height: 84px;
      display: flex;
      align-items: center;
      justify-content: center;
      position: absolute;
      top: 0;
      left: -100%;

      .van-icon {
        transition: all linear .2s;
        position: absolute;
        left: 0;
        top: 0;
        font-size: 64px;
        color: #fff;
      }
    }
  }

  .counts {
    display: block;
    padding: 0 15px;
    line-height: 30px;
    font-size: 24px;
    color: #000;
    background-color: rgba(0,0,0,.3);
    border-radius: 15px;
  }
}


.input-bar {
  display: flex;
  height: 104px;
  padding: 14px 0;
  align-items: center;
  background-color: #f7f7f7;

  .button-send {
    width: 80px;
    height: 76px;
    font-size: 28px;
    line-height: 76px;
    position: absolute;
    right: 15px;
    text-align: center;
    color: #fff;
    background-color: $blue;
    border-radius: 6px;
  }

  .icon-box {
    padding: 0 15px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 56px;
    color: $face-color;
    i {
        display: flex;
        width: 50px;
        height: 50px;
        align-items: center;
        justify-content: center;
        text-align: center;
      }
  }

    .icon-gift-box {
        width: 50px;
        height: 50px;
        padding: 0;
        margin-left: 20px;
        //background: linear-gradient(linear, left top, right bottom, from(#fe5c48), to(#fc2876));
        background: linear-gradient(#fe5c48, #fc2876);
        border-radius: 100%;
    }

  .input-text {
    width: 489px;
    height: 76px;
    padding-left: 20px;
    border: 1px solid #eceded;
    font-size: 26px;
    background-color: #fff;
    box-shadow: none;
    outline: none;
  }

  .input-box pre {
    width: 490px;
    height: 76px;
    padding-top: 5px;
    line-height: 66px;
    padding-left: 20px;
    border: 1px solid #eceded;
    outline: none;
    font-size: 26px;
    overflow: hidden;
    overflow-y: auto;
    white-space: pre-wrap;
    background-color: #fff;
  }
}


.option-groups-panel {
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 100;
}

.popup-gift {
    position: absolute;
}

canvas {
	display: block;
	position: absolute;
	top: 0;
	right: 60px;
	z-index: 20;
	cursor: pointer;
    background: yellowgreen;
    z-index: 20;;
	-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
</style>